const { formatDate } = require('../../utils/util');  // 引入格式化函数
Page({
  data: {
    question: null,  // 问题详情
    replies: [],     // 回复列表
    replyContent: '',  // 输入的回复内容
    parentReplyNickname: '',  // 父回复昵称
    parentReplyId: null,  // 父回复ID
    pageNum: 1,
    pageSize: 20,
  },

  onLoad: function(options) {
    const questionId = options.id;  // 获取传递的 questionId
    this.loadQuestion(questionId);  // 请求问题详情数据
    this.loadQuestionReplies(questionId, this.data.pageNum, this.data.pageSize);  // 请求问题回复数据
  },

  loadQuestion: function(questionId) {
    wx.request({
      url: `http://localhost:9090/psychologicalQaQuestions/${questionId}`,  // 请求问题详情接口
      method: 'GET',
      success: (res) => {
        if (res.data) {
          this.setData({
            question: res.data,  // 设置问题详情
          });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '加载问题失败', icon: 'none' });
      }
    });
  },

  loadQuestionReplies: function(questionId, pageNum, pageSize) {
    wx.request({
      url: `http://localhost:9090/qaReplies/${questionId}`,
      method: 'GET',
      data: {
        pageNum: pageNum,
        pageSize: pageSize,
      },
      success: (res) => {
        if (res.data) {
          const formattedReplies = this.processReplies(res.data.list);
          this.setData({
            replies: formattedReplies, // 设置处理后的回复数据
          });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '加载回复失败', icon: 'none' });
      }
    });
  },

  processReplies: function(replies) {
    let parentReplies = [];
    let replyMap = {};
    replies.forEach(reply => {
      reply.children = reply.children || [];
      replyMap[reply.replyId] = reply;
    });

    replies.forEach(reply => {
      if (!reply.parentReplyId) {
        parentReplies.push(reply);
      } else {
        const parentReply = replyMap[reply.parentReplyId];
        if (parentReply) {
          reply.parentMemberNickname = parentReply.members.nickname;
          parentReply.children.push(reply);
        }
      }
    });

    parentReplies = this.limitReplies(parentReplies);
    return parentReplies;
  },

  limitReplies: function(replies, level = 1) {
    return replies.map(reply => {
      if (level < 3 && reply.children && reply.children.length > 0) {
        reply.children = this.limitReplies(reply.children, level + 1);
      }
      return reply;
    });
  },

  // 点击回复按钮，显示@父回复昵称
  onReplyClick: function(e) {
    const replyId = e.currentTarget.dataset.replyid;  // 获取当前回复的ID
    const nickname = e.currentTarget.dataset.nickname;  // 获取当前回复的昵称

    console.log('点击回复按钮传递的回复ID:', replyId);
    console.log('点击回复按钮传递的回复昵称:', nickname);

    // 设置父回复信息
    this.setData({
      replyContent: `@${nickname} `,  // 在输入框显示父回复的昵称
      parentReplyId: replyId,  // 设置父回复ID
      parentReplyNickname: nickname,  // 设置父回复昵称
    });
  },

  // 监听输入框的输入事件
  onInput: function(e) {
    this.setData({
      replyContent: e.detail.value,  // 更新输入的回复内容
    });
  },

  // 提交回复
  onSubmitReply: function() {
    const user = wx.getStorageSync('vipuser');  // 获取当前用户信息
    if (!user) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    const questionId = this.data.question.questionId;  // 获取当前问题的 ID
    const replyContent = this.data.replyContent.trim();  // 获取回复内容
    const parentReplyId = this.data.parentReplyId;  // 获取父回复ID

    if (!replyContent) {
      wx.showToast({ title: '请输入回复内容', icon: 'none' });
      return;
    }

    // 提交时去掉 @父回复昵称 的部分
    const pureReplyContent = replyContent.replace(/^@[^ ]+ /, '');  // 移除 @父回复昵称

    // 创建回复对象
    const replyData = {
      replyContent: pureReplyContent,  // 提交纯文本内容
      memberId: user.memberId,  // 使用当前用户的 ID
      replyTime: formatDate(new Date()),  // 格式化当前时间
      questionId: questionId,
      parentReplyId: parentReplyId,  // 回复问题或父回复
    };

    // 发送请求到后台接口
    wx.request({
      url: 'http://localhost:9090/qaReplies',  // 添加回复的接口
      method: 'POST',
      data: replyData,
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '回复成功', icon: 'success' });
          // 回复成功后，刷新回复列表
          this.loadQuestionReplies(questionId, this.data.pageNum, this.data.pageSize);
          this.setData({
            replyContent: '',  // 清空输入框内容
            parentReplyId: null,  // 重置父回复ID
            parentReplyNickname: '',  // 重置父回复昵称
          });
        } else {
          wx.showToast({ title: '回复失败', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '回复失败', icon: 'none' });
      }
    });
  },
});
